package com.skymxc.demo.explorer;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.skymxc.demo.explorer.adapter.FileAdapter;
import com.skymxc.demo.explorer.core.FileTask;
import com.skymxc.demo.explorer.core.FileType;
import com.skymxc.demo.explorer.core.SortType;
import com.skymxc.demo.explorer.entity.PageTab;
import com.skymxc.demo.explorer.util.FileUtil;
import com.skymxc.demo.explorer.util.SettingUtil;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import static com.skymxc.demo.explorer.R.id.send;

/**
 * Created by sky-mxc
 */

public class TabFragment extends Fragment {

    private static final String TAG="TabFragment";
    private View view;
    private TextView tvSdInfo;
    private GridView gv;
    private PageTab tab;
    private FileAdapter adapter;
    private ActionMode actionMode;
    private List<File> selectedFiles;

    private File currentFile;


    private boolean moveFileDeleteSource;

    public TabFragment(){

        this.setArguments(new Bundle());

    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view==null){
            view = inflater.inflate(R.layout.layout_fragment_tab,null);
            tvSdInfo = (TextView) view.findViewById(R.id.sdcard_info);
            gv = (GridView) view.findViewById(R.id.grid_view);
        }
        tvSdInfo.setText(FileUtil.getSDCardInfo(getContext()));
        tab = (PageTab) getArguments().getSerializable("tab");
       // Log.e(TAG,"createView()");
        //初始化ListView
        if (tab!=null){
            //是否记住路径
            if (currentFile!=null){
                Log.e(TAG,"===before :"+currentFile.getPath());
            }else {
                if (SettingUtil.isRememberPath(getContext())) {
                    currentFile = new File(tab.getLastPath());
                } else {
                    currentFile = new File(tab.getMainPath());
                }
            }

          //  Log.e(TAG,"===behind :"+currentFile.getPath());


            adapter = new FileAdapter(getContext(), null);
            adapter.setFiles(getDirectory());
            adapter.setSelectedChangeListener(onSelectedChangedListener);

            //显示模式不同 列数不同
            if (SettingUtil.getShowMode(getContext())==2){
                //网格 自适应
                gv.setColumnWidth(getContext().getResources().getDimensionPixelSize(R.dimen.grid_item_icon_width));
                gv.setNumColumns(GridView.AUTO_FIT);
                int span = getContext().getResources().getDimensionPixelSize(R.dimen.grid_item_span);
                gv.setHorizontalSpacing(span);
                gv.setVerticalSpacing(span);
            }else{
                gv.setColumnWidth(0);
                gv.setNumColumns(1);
                gv.setVerticalSpacing(0);
                gv.setHorizontalSpacing(0);

            }

            gv.setAdapter(adapter);
            gv.setOnItemClickListener(onItemClickListener);
            gv.setOnItemLongClickListener(itemLongClickListener);
                setToolBarTitle();



        }

        return view;
    }


    /**
     * 长按事件 触发 显示 复选框 并选择
     */
    private AdapterView.OnItemLongClickListener itemLongClickListener = new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            //屏蔽返回上一级
            if (!currentFile.equals(Environment.getExternalStorageDirectory()) && position ==0){
                return true;
            }

            adapter.toggleSelectFile(position);

            return true;
        }
    };
    /**
     * 文件选中的改变监听 用来改变ActionMode
     */
    private FileAdapter.OnSelectedChangedListener onSelectedChangedListener = new FileAdapter.OnSelectedChangedListener() {
        @Override
        public void onSelectedChanged(List<File> selectedFiless) {
            selectedFiles= selectedFiless;
            if (selectedFiles.isEmpty()){
                if (actionMode!=null) {
                    actionMode.finish();
                    actionMode = null;
                }
            }else{

                if (actionMode == null){
                    actionMode= getActivity().startActionMode(callBack);
                  //  Log.e(TAG,"===actionMode:"+actionMode);
                    actionMode.setTitle("选择项目");
                }
                actionMode.setSubtitle(String.format("已选中%d项",selectedFiles.size()));
                setActionModeMenu(selectedFiles);
            }
        }
    };

    /**
     * 设置 ActionMode的菜单
     * @param selectedFiles
     */
    private void setActionModeMenu(List<File> selectedFiles) {

        if (actionMode==null ) return;
        int num = actionMode.getTag() == null?0: (int) actionMode.getTag();
        int current = selectedFiles.size();
        if (num >=2 && current>=2) return;
        int menuRes;
        if (selectedFiles.size() ==1){
            File file = selectedFiles.get(0);
            FileType type = FileType.parseFile(file);
            if (type == FileType.DIR){
                menuRes = R.menu.menu_select_dir;
            }else if (type == FileType.ZIP){
                menuRes = R.menu.menu_select_file_zip;
            }else{
                menuRes =R.menu.menu_select_file;
            }
        }else{//选择多项 时
            menuRes = R.menu.menu_muitt_select;
        }
        actionMode.getMenu().clear();
        getActivity().getMenuInflater().inflate(R.menu.menu_select_public,actionMode.getMenu());
        getActivity().getMenuInflater().inflate(menuRes,actionMode.getMenu());
    }

    private ActionMode.Callback callBack = new ActionMode.Callback() {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {

            menuItemClick(item);

            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            //取消选中操作
            adapter.clearAllSelected();
            actionMode = null;
        }
    } ;

    /**
     * 菜单项点击事件
     * @param item
     */
    private void menuItemClick(MenuItem item) {
        switch (item.getItemId()){
            case R.id.set_main_dir:
                tab.setMainPath(selectedFiles.get(0).getPath());
                tab.save();

                Toast.makeText(getActivity(),"设置成功",Toast.LENGTH_SHORT).show();
                break;
            case R.id.rename:
                rename();
                break;
            case send:
            //intent 发送 隐式意图发送
                sendFile();
                break;
            case R.id.all:
                adapter.selectAll();
                break;
            case R.id.del:
               delFile();
                break;
            case R.id.info:
                showFileInfo();
                break;
            case R.id.copy:
                moveFile(true);
                break;
            case R.id.cut:
                moveFile(false);
                break;
            case R.id.compress:
                compress();
                break;
            case R.id.uncompress:
                uncompress();
                break;
        }
    }

    /**
     * 解压
     */
    private void uncompress() {
        actionMode.finish();
        FileTask task = new FileTask(getContext(),selectedFiles,FileTask.UNCOMPRESS);
        task.execute();

    }

    /**
     * 压缩
     */
    private void compress() {
        actionMode.finish();
        FileTask task = new FileTask(getContext(),selectedFiles,FileTask.COMPRESS);
        task.execute();
    }

    /**
     * 移动文件
     * @param deleteSource 是否删除原文件
     */
    private void moveFile(boolean deleteSource) {
        actionMode.finish();
        moveFileDeleteSource = deleteSource;
        ((MainActivity)  getActivity()).moveFile();
    }

    public void move(){
       // if (currentFile.equals(selectedFiles.get(0))) return;
        FileTask task = new FileTask(getContext(),selectedFiles,moveFileDeleteSource?FileTask.COPY:FileTask.CUT);
        task.execute();
        task.setOnCompleteLis(new FileTask.OnCompleteListener() {
            @Override
            public void onComplete() {
            refresh();
            }

        });
        task.setParentFile(currentFile);
    }

    /**
     * 显示文件信息
     */
    private void showFileInfo() {
        actionMode.finish();
        String info = FileUtil.getDetailFileInfo(getContext(),selectedFiles.get(0));
        new AlertDialog.Builder(getActivity())
                .setTitle("属性")
                .setMessage(info)
                .setNegativeButton("确定",null)
                .show();
    }

    /**
     * 删除文件
     */
    private void delFile() {
        actionMode.finish();
        FileTask task = new FileTask(getContext(),selectedFiles,FileTask.DELETE);
        task.execute();
        task.setOnCompleteLis(new FileTask.OnCompleteListener() {
            @Override
            public void onComplete() {
                refresh();
            }
        });
        }




    /**
     * 发送文件
     */
    private void sendFile() {
        actionMode.finish();
        Intent in = new Intent(Intent.ACTION_SEND);
        FileType type = FileType.parseFile(selectedFiles.get(0));
        switch (type){
            case AUDIO:
                in.setType("audio/mp3");
                break;
            case IMAGE:
                in.setType("image/*");
                break;
            case VIDEO:
                in.setType("video/*");
            default:
                in.setType("*");
                break;
        }

        in.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(selectedFiles.get(0)));
        startActivity(Intent.createChooser(in,"选择要发送的平台吧"));

    }

    /**
     * 重命名
     */
    private void rename() {
        actionMode.finish();
        //获取选中的文件
        final File currentFile = selectedFiles.get(0);
        String name= currentFile.getName();
        if (currentFile.isFile()){
            //抹掉后缀
            name=currentFile.getName().substring(0,currentFile.getName().lastIndexOf("."));
        }
        final EditText edit = new EditText(getActivity());
        edit.setText(name);
        new AlertDialog.Builder(getActivity()).setTitle("重命名")
                .setView(edit)
                .setNeutralButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String rename = edit.getText().toString();
                        File file = null;
                        if (currentFile.isDirectory()){
                            file = new File(currentFile.getParent(),rename);
                        }else{
                            file = new File(currentFile.getParent(),rename+currentFile.getName().substring(currentFile.getName().indexOf(".")));
                        }

                        currentFile.renameTo(file);
                        ((MainActivity)getActivity()).refreshAllFragment();
                    }
                }).setNegativeButton("cancel",null)
                .show();

    }


    //文件点击事件
    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            File file = adapter.getItem(position);

            if (adapter.isSelectFileStatus()){
                adapter.toggleSelectFile(position);
            }else {


                if (file.isDirectory()) {
                    currentFile = file;
                    adapter.setFiles(getDirectory());
                } else {

                }
                setToolBarTitle();
            }
        }
    };

    public void setToolBarTitle() {
       // Log.e(TAG,"==setToolBarTitle()==");
        ( (Toolbar)  getActivity().findViewById(R.id.tool_bar)).setTitle(currentFile.getName());
        ( (Toolbar)  getActivity().findViewById(R.id.tool_bar)).setSubtitle(currentFile.getPath());
    }

    /**
     * 获取 子文件集合
     * @return
     */
    @NonNull
    private List<File> getDirectory() {
        tab.setLastPath(currentFile.getPath());
        tab.save();
        LinkedList<File> files = new LinkedList(FileUtil.loadAllChildren(currentFile, SettingUtil.isShowHideFile(getContext()), SortType.parse(SettingUtil.getSortType(getContext()))));

        //当前目录 != 根目录
        if (!currentFile.equals(Environment.getExternalStorageDirectory())){
            files.addFirst(currentFile.getParentFile());
            adapter.setRoot(false);
        }else{
            adapter.setRoot(true);
        }
        return files;
    }



    /**
     * 刷新数据
     */
    public void refresh() {

        adapter.setFiles(getDirectory());
        if (SettingUtil.getShowMode(getContext())==2){
            //网格 自适应
            gv.setColumnWidth(getContext().getResources().getDimensionPixelSize(R.dimen.grid_item_icon_width));
            gv.setNumColumns(GridView.AUTO_FIT);
            int span = getContext().getResources().getDimensionPixelSize(R.dimen.grid_item_span);
            gv.setHorizontalSpacing(span);
            gv.setVerticalSpacing(span);
        }else{
            gv.setColumnWidth(0);
            gv.setNumColumns(1);
            gv.setVerticalSpacing(0);
            gv.setHorizontalSpacing(0);

        }
    }

    /**
     * 新建文件或者文件夹
     * @param type
     * @param name
     */
    public boolean createFile(int type, String name) {
        File file = new File(currentFile,name);
        boolean result=false;
        if (type == R.id.new_directory){
            //文件夹
           result=file.mkdir();
        }else{
            //文件
            try {
              result=file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  result;
    }


    /**
     * 返回主文件夹
     */
    public void returnMain() {
        currentFile= Environment.getExternalStorageDirectory();
        refresh();
        setToolBarTitle();
    }


    /**
     * 返回或者退出
     * @return
     */
    public boolean onBackPressed() {
        if (!currentFile.equals(Environment.getExternalStorageDirectory())){
            currentFile= currentFile.getParentFile();
            refresh();
            setToolBarTitle();
            return  false;
        }
       return  true;

    }

    /**
     * 隐藏ActionMode
     */
    public void hideActionMode() {
        if(actionMode!=null){
            actionMode.finish();
            actionMode=null;
        }
    }
}
